package com.yygo.webapp.controller;

import com.yygo.model.*;
import com.yygo.service.*;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;

@Controller
@RequestMapping("/importcity*")
public class ImportCityController extends BaseFormController {

    private static final Log log = LogFactory.getLog(ImportCityController.class);

    private ProvinceManager provinceManager;
    private CityManager cityManager;
    private CountyManager countyManager;

    @Autowired
    public void setProvinceManager(ProvinceManager provinceManager) {
        this.provinceManager = provinceManager;
    }

    @Autowired
    public void setCityManager(CityManager cityManager) {
        this.cityManager = cityManager;
    }

    @Autowired
    public void setCountyManager(CountyManager countyManager) {
        this.countyManager = countyManager;
    }

    public ImportCityController() {
        setCancelView("redirect:/home");
        setSuccessView("importCitySuccess");
    }

    @ModelAttribute
    @RequestMapping(method = RequestMethod.GET)
    public FileUpload showForm() {
        return new FileUpload();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(FileUpload fileUpload, BindingResult errors, HttpServletRequest request)
            throws Exception {

        if (request.getParameter("cancel") != null) {
            return getCancelView();
        }

        if (validator != null) { // validator is null during testing
            validator.validate(fileUpload, errors);

            if (errors.hasErrors()) {
                return "importcity";
            }
        }

        // validate a file was entered
        if (fileUpload.getFile().length == 0) {
            Object[] args =
                    new Object[]{getText("uploadForm.file", request.getLocale())};
            errors.rejectValue("file", "errors.required", args, "File");

            return "importcity";
        }

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");

        //retrieve the file data
        InputStream stream = file.getInputStream();

        log.debug("clear up all city data.");
        provinceManager.clearAll();
        int count = importCity(stream);
        log.debug(count + " vehicles have been imported.");
        //close the stream
        stream.close();

        // place the data into the request for retrieval on next page
        request.setAttribute("cityCount", count);

        return getSuccessView();
    }

   private int importCity(InputStream is) {
        int count = 0;
        try {
            Workbook rwb = Workbook.getWorkbook(is);
            Sheet st = rwb.getSheet(0);

            int rs=st.getColumns();
            int rows=st.getRows();

            Province provinceObj = null;
            City cityObj = null;

            for(int k = 0;k < rows; k++){
                String province = st.getCell(0,k).getContents();
                String secondValue = st.getCell(1,k).getContents();

                if (!province.equals("")) {
                    String code = secondValue;
                    provinceObj = new Province(province, code);
                    provinceObj = provinceManager.save(provinceObj);
                } else if (!secondValue.equals("")) {
                    String city = secondValue;
                    cityObj = new City(city);
                    cityObj.setProvince(provinceObj);
                    cityObj = cityManager.save(cityObj);
                    count++;

                    String thirdValue = st.getCell(2,k).getContents();
                    String[] counties = thirdValue.split("(\\s)*,(\\s)*");
                    for (String county : counties) {
                        if (!county.equals("")) {
                            County countyObj = new County(county);
                            countyObj.setCity(cityObj);
                            //log.debug("importing city: " + countyObj.toString());
                            countyManager.save(countyObj);
                        }
                    }
                }
            }

        }catch (Exception ex) {
            ex.printStackTrace();
        }

       return count;
    }


}
